package com.example.demo.boot.filter;

import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p> ServletRequest缓存过滤器 </p>
 * 解决Spring中采用application/json方式接收body参数时getInputStream无法复用的bug StreamFilter
 * 使用ContentCachingRequestWrapper来包装HttpServletRequest，
 * 使用ContentCachingResponseWrapper来包装HttpServletResponse
 *
 * @author tanyunpeng
 * @date 2021/11/19
 */
@WebFilter(filterName = "streamFilter", value = "/*")
public class StreamFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper((HttpServletRequest) request);
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(
                (HttpServletResponse) response);
        try {
            chain.doFilter(requestWrapper, responseWrapper);
        } finally {
            responseWrapper.copyBodyToResponse();
        }
    }

    @Override
    public void destroy() {
    }
}